package cn.xiaohuodui.service;

import cn.xiaohuodui.constant.ErrorCodeDefine;
import cn.xiaohuodui.dao.*;
import cn.xiaohuodui.dic.BannerPosition;
import cn.xiaohuodui.exceptions.BussException;
import cn.xiaohuodui.form.back.good.BackGoodDo;
import cn.xiaohuodui.form.back.good.BackGoodQueryForm;
import cn.xiaohuodui.form.good.SearchForm;
import cn.xiaohuodui.model.*;
import cn.xiaohuodui.res.JsonRes;
import cn.xiaohuodui.util.SortUtil;
import cn.xiaohuodui.vo.GoodCategoryAttribute.GoodCateAttVo;
import cn.xiaohuodui.vo.Sku.SkuVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.stereotype.Service;
import cn.xiaohuodui.form.back.good.BackGoodCreateForm;
import cn.xiaohuodui.model.GoodWithBLOBs;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by TR on 2018/4/2.
 */
@Service
public class GoodService {

    @Autowired
    GoodMapper goodMapper;

    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    SearchHistoryMapper searchHistoryMapper;

    @Autowired
    BannerMapper bannerMapper;

    @Autowired
    BrandMapper brandMapper;

    @Autowired
    GoodCateAttService goodCateAttService;

    @Autowired
    SkuService skuService;

    @Autowired
    GoodSkuService goodSkuService;

    @Autowired
    GoodSkuAttService goodSkuAttService;

    @Autowired
    IssueMapper issueMapper;

    @Autowired
    CommentMapper commentMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    CollectService collectService;

    @Autowired
    FootPrintMapper footPrintMapper;


    /**
     * 统计所有已上架且未删除的商品总数
     *
     * @return
     */
    public JsonRes<Map<String, Object>> count() {
        Map<String, Object> map = new HashMap<>();
        map.put("goodsCount", goodMapper.count());
        return JsonRes.createBySuccessData(map);
    }


    public JsonRes<Map<String, Object>> getGoodsByCate(Integer id) {

        Category cur = categoryMapper.selectByPrimaryKey(id);
        List<Category> children = null;

        if (cur.getParentId() == 0) {  //若是一级类目
            children = categoryMapper.getChildrensByPid(cur.getId());
        } else {  //若是二级类目
            children = categoryMapper.getChildrensByPid(cur.getParentId());
        }
        Map<String, Object> data = new HashMap();
        data.put("currentCategory", cur);
        data.put("parentCategory", children);
        data.put("brotherCategory", children);
        return JsonRes.createBySuccessData(data);
    }


    public JsonRes<Map<String, Object>> list(SearchForm searchForm) {
        String sortWithOrder = SortUtil.goodsSort(searchForm.getSort(), searchForm.getOrder());
        searchForm.setSortWithOrder(sortWithOrder);
        //添加到搜索历史
        if (searchForm.getUserId() != null && !StringUtils.isEmpty(searchForm.getKeyword())) {
            SearchHistory searchHistory = new SearchHistory();
            searchHistory.setAddTime(System.currentTimeMillis());
            searchHistory.setKeyword(searchForm.getKeyword());
            searchHistory.setUserId(searchForm.getUserId());
            searchHistory.setFrom("wx_mini");
            searchHistoryMapper.insert(searchHistory);
        }

        Category category = categoryMapper.selectByPrimaryKey(searchForm.getCategoryId());
        if (category != null) {
            if (category.getParentId() == 0) {
                searchForm.setCategory2Id(null);
            } else {
                searchForm.setCategory2Id(category.getId());
                searchForm.setCategoryId(null);
            }
        }


        //查询列表数据
        List<Good> goodsList = goodMapper.querySelective(searchForm.toMap());

        int total = goodMapper.countSelective(searchForm.toMap());

        // 查询商品所属二级类目列表。
        List<Category> categories = goodsList.stream().map(e -> {
            return categoryMapper.selectByPrimaryKey(e.getCategory2Id());
        }).collect(Collectors.toList());

        Map<String, Object> data = new HashMap();
        data.put("goodsList", goodsList);
        data.put("filterCategoryList", categories);
        data.put("count", total);
        return JsonRes.createBySuccessData(data);
    }


    public JsonRes<Map<String, Object>> newGoodsBanner() {
        Map<String, Object> data = new HashMap();
        List<Banner> byPosition = bannerMapper.getByPosition(BannerPosition.NEW_GOODS.getVal());
        data.put("bannerInfo", byPosition.get(0));
        return JsonRes.createBySuccessData(data);
    }


    public JsonRes<Map<String, Object>> hotGoodsBanner() {
        Map<String, Object> data = new HashMap();
        List<Banner> byPosition = bannerMapper.getByPosition(BannerPosition.HOT_GOODS.getVal());
        data.put("bannerInfo", byPosition.get(0));
        return JsonRes.createBySuccessData(data);
    }

    public JsonRes<Map<String,Object>> detail(Integer userId,Integer id) throws BussException {
        // 商品信息
        GoodWithBLOBs goodWithBLOBs = goodMapper.selectByPrimaryKey(id);
        String[] split ={};
        if(!StringUtils.isEmpty(goodWithBLOBs.getGallery())){
            split=goodWithBLOBs.getGallery().split(",");
        }

        goodWithBLOBs.setGalleryArray(split);


        if(goodWithBLOBs==null) {
            throw new BussException(ErrorCodeDefine.GOOD_NOT_EXIST.getCode(),ErrorCodeDefine.GOOD_NOT_EXIST.getDesc());
        }

        //商品所在二级类目所有属性
        List<GoodCateAttVo> byGoodId = goodCateAttService.getByGoodId(goodWithBLOBs.getId());

        // 商品规格
        // 返回的是定制的SkuVo
        List<SkuVo> skuVos = goodSkuService.getByGoodId(id);

        // 商品规格对应的数量和价格
        List<GoodSkuAttribute> goodSkuAttributes = goodSkuAttService.getByGoodId(id);

        // 商品问题，这里是一些通用问题
        List<Issue> issues = issueMapper.query();

        // 商品品牌商
        Brand brand = brandMapper.selectByPrimaryKey(goodWithBLOBs.getBrandId());

        // 评论(前两个)
        List<Comment> comments = commentMapper.queryGoodsByVid(id);

        List<Map<String, Object>> commentsVo = new ArrayList<>(comments.size());
        int commentCount =commentMapper.countByVid(id);//评论总数
        for(Comment comment : comments){
            Map<String, Object> c = new HashMap<>();
            c.put("id", comment.getId());
            c.put("addTime", comment.getCreated());
            c.put("content", comment.getContent());
            User user = userMapper.selectByPrimaryKey(comment.getUserId());
            c.put("nickname", user.getNickname());
            c.put("avatar", user.getAvatar());
            c.put("picList", comment.getPicUrls());
            commentsVo.add(c);
        }
        Map<String, Object> commentList = new HashMap();
        commentList.put("count", commentCount);
        commentList.put("data", commentsVo);

        // 用户收藏
        int userHasCollect = 0;
        if(userId != null) {
            userHasCollect = collectService.hasCollect(userId, id);
        }

        // 记录用户的足迹
        if(userId != null) {
            FootPrint footprint = new FootPrint();
            footprint.setCreated(System.currentTimeMillis());
            footprint.setUserId(userId);
            footprint.setGoodId(id);
            footPrintMapper.insert(footprint);
        }

        Map<String, Object> data = new HashMap();
        data.put("info", goodWithBLOBs);
        data.put("userHasCollect", userHasCollect);
        data.put("issue", issues);
        data.put("comment", comments);
        data.put("skuVos", skuVos);
        data.put("goodSkuAttributes", goodSkuAttributes);
        data.put("attribute", byGoodId);
        data.put("brand", brand);
        return JsonRes.createBySuccessData(data);
    }


    public JsonRes<Map<String,Object>> related(Integer goodId) throws BussException {

        GoodWithBLOBs goodWithBLOBs = goodMapper.selectByPrimaryKey(goodId);
        if(goodWithBLOBs==null){
            throw new BussException(ErrorCodeDefine.GOOD_NOT_EXIST.getCode(),ErrorCodeDefine.GOOD_NOT_EXIST.getDesc());
        }
        int cid = goodWithBLOBs.getCategory2Id();

        // 查找六个相关商品
        int related = 6;
        List<Good> goodsList = goodMapper.queryByCategory(cid,related);
        Map<String, Object> data = new HashMap();
        data.put("goodsList", goodsList);

        return JsonRes.createBySuccessData(data);
    }





    // ------------------------------------------------> 以下为后台代码

    /**
     * 新建商品
     *
     * @param backGoodCreateForm
     * @return
     */
    public GoodWithBLOBs createGood(BackGoodCreateForm backGoodCreateForm) {
        GoodWithBLOBs good = new GoodWithBLOBs();
        BeanUtils.copyProperties(backGoodCreateForm, good);
        good.setCreated(System.currentTimeMillis());
        good.setUpdated(good.getCreated());
        good.setDeleted(Byte.valueOf("0"));
        goodMapper.insert(good);
        return good;
    }

    /**
     * 查询 商品数量
     *
     * @param form
     * @return
     */
    public int goodBackCount(BackGoodQueryForm form) {
        Map qm = new HashMap();
        qm.put("name", form.getName());
        qm.put("num", form.getNum());
        qm.put("brandId", form.getBrandId());
        qm.put("isOnSale", form.getIsOnSale());
        qm.put("startTime", form.getStartTime());
        qm.put("endTime", form.getEndTime());
        qm.put("isNew", form.getIsNew());
        qm.put("isHot", form.getIsHot());

        return goodMapper.goodBackCount(qm);
    }

    /**
     * 查询 商品
     *
     * @param form
     * @return
     */
    public List<BackGoodDo> goodBackQuery(BackGoodQueryForm form) {
        Map qm = new HashMap();
        qm.put("limit", form.getLimit());
        qm.put("offset", form.getOffset());

        qm.put("name", form.getName());
        qm.put("num", form.getNum());
        qm.put("brandId", form.getBrandId());
        qm.put("isOnSale", form.getIsOnSale());
        qm.put("startTime", form.getStartTime());
        qm.put("endTime", form.getEndTime());
        qm.put("isNew", form.getIsNew());
        qm.put("isHot", form.getIsHot());

        List<Good> goodList = goodMapper.goodBackQuery(qm);
        if (CollectionUtils.isEmpty(goodList)) {
            return new ArrayList<>();
        }
        return goodList.stream().map(eachListDo -> {
            BackGoodDo goodDo = new BackGoodDo();
            BeanUtils.copyProperties(eachListDo, goodDo);
//            ActivityPublish activity = activityPublishMapper.selectByPrimaryKey(eachListDo.getActivityId());
//            if (activity != null){
//                goodDo.setTitle(activity.getTitle());
//                ActivityGoods good = activityGoodsMapper.selectByPrimaryKey(activity.getActivityGoodId());
//                if (good != null) {
//                    CropType cropType = cropTypeMapper.selectByPrimaryKey(good.getCropTypeId());
//                    goodDo.setCropTypeName(cropType.getTypeName());
//                    goodDo.setCropName(good.getGoodsName());
////                    activityOrderDo.setWeight(good.getWeight());
////                    activityVo.setAmount(good.getAmount());
////                    activityVo.setUsed(good.getUsed());
//                    goodDo.setYear(good.getYear());
////                    activityVo.setOrigin(good.getOrigin());
////                    activityVo.setCropIntro(cropType.getIntro());
//                }
//            }

            return goodDo;

        }).collect(Collectors.toList());
    }
}
